// Polygon.java
// by Alexandre Martins, 2013
// MAC 5857 - Prof. Leonidas

package example.ilm.model;

import ilm.framework.assignment.model.DomainObject;
import example.ilm.gui.Polygon2D;

import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
import java.awt.geom.AffineTransform;
import java.awt.Color;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

public abstract class Polygon extends Shape {

    /**
     * my data
     */
    protected double angle;

    /**
     * constructor
     */
    public Polygon(String elementName) {
        super(elementName);
        angle = 0.0;
    }

    // ---------- get/set -------------
    public double getAngle() { return angle; }
    public void setAngle(double a) { angle = a; }
    // ---------- get/set -------------

    /**
     * verifica se um ponto esta' dentro do objeto
     */
    public boolean contains(Point2D p) {
        Polygon2D p2d = new Polygon2D();
        Iterator it = this.getTransformedVertices().iterator();
        while(it.hasNext()) {
            Point2D q = (Point2D)(it.next());
            p2d.addPoint((float)q.getX(), (float)q.getY());
        }
        return p2d.contains(p);
    }

    /**
     * pega os vertices ja transformados (transf. afim)
     */
    public List getTransformedVertices() {
        AffineTransform t = new AffineTransform();
        t.setToIdentity();
        t.translate(this.getPosition().getX(), this.getPosition().getY());
        t.rotate(this.getAngle());
        t.scale(this.getScale(), this.getScale());

        List transformedVertices = new ArrayList();
        Iterator it = getVertices().iterator();
        while(it.hasNext()) {
            Point2D p = (Point2D)(it.next());
            Point2D q = t.transform(p, null);
            transformedVertices.add(q);
        }

        return transformedVertices;
    }

    /**
     * Convert this object to a XML String, placing the fields between the
     * fields' names.
     */
    public String toString() {
        return "" + 
            "<polygon>" + 
                "<name>" + getName() + "</name>" + 
                "<description>" + getDescription() + "</description>" + 
                "<position>" +
                    positionToString() +
                "</position>" + 
                "<scale>" + scale + "</scale>" +
                "<angle>" + angle + "</angle>" +
                "<color>" +
                    colorToString() + 
                "</color>" +
                "<vertices>" +
                    verticesToString() +
                "</vertices>" +
            "</polygon>" +
        "";
    }
}
